package com.bmmtwabp.employeedashbord.websocket;

import com.bmmtwabp.employeedashbord.util.WebSocketUtil;
import java.io.IOException;
import java.util.Date;
import javax.websocket.*;
import javax.websocket.Session;
import javax.websocket.server.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @Description: websocket-controller
 * @Param:
 * @return:
 * @Author: fenghouzhi
 * @Date: 5:09 PM 2018/10/22
 */
@Slf4j
@Component
@ServerEndpoint(value = "/websocket/{openId}")
public class WebSocketController {

  /**
   * 连接socket，上线
   */
  @OnOpen
  public void onOpen(@PathParam(value = "openId") String openId, Session session) {
    String message = "有新用户[" + openId + "]进入队列";
    log.info("meg info:   " + message);
    WebSocketUtil.addSession(openId, session);
    WebSocketUtil.sendMessageForAll(message);
  }

  /**
   * 下线socket
   */
  @OnClose
  public void onClose(@PathParam(value = "openId") String openId, Session session) {
    String message = "用户[" + openId + "]退出队列";
    log.info("msg info:   " + message);
    WebSocketUtil.removeSession(openId);
    WebSocketUtil.sendMessageForAll(message);
  }

  /**
   * 发送消息
   */
  @OnMessage
  public void onMessage(@PathParam(value = "openId") String openId, String message) {
    log.info("openId info:   " + openId);
    String[] msgArray = message.split(",");
    String type = msgArray[0];
    String msg = msgArray[1];
    switch (type) {
      /**
       * 广播消息
       */
      case "0":
        WebSocketUtil.sendMessageForAll(msg);
        break;
      /**
       * 心跳消息
       */
      case "1":
        String heartMsg = "服务器的心跳回应-HeartBeat" + new Date();
        WebSocketUtil.serverToClientMsg(openId, heartMsg);
        break;
      /**
       * 群组消息
       */
      case "2":
        break;
      default:
        break;
    }
  }

  /**
   * socket方法异常
   */
  @OnError
  public void onError(Session session, Throwable throwable) {
    log.error("异常:", throwable);
    try {
      session.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
    throwable.printStackTrace();
  }

}